package com.gc.libnet

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException

import org.json.JSONException
import retrofit2.HttpException

import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException
import javax.net.ssl.SSLHandshakeException


object DealException {

    fun <T> handlerException(t: Throwable): RestfulResponse<T> {
        var errCode: Int = 0
        var errMsg: String = ""
        if (t is HttpException) {
            errCode = t.code()
            errMsg= when (t.code()) {

                HttpManager.UNAUTHORIZED,
                HttpManager.FORBIDDEN,
                    //权限错误，需要实现
                HttpManager.NOT_FOUND,
                -> "网络错误"
                HttpManager.REQUEST_TIMEOUT,
                HttpManager.GATEWAY_TIMEOUT,
                -> "网络连接超时"
                HttpManager.INTERNAL_SERVER_ERROR,
                HttpManager.BAD_GATEWAY,
                HttpManager.SERVICE_UNAVAILABLE,
                -> "服务器错误"
                else ->  "网络错误"
            }
        } else if (t is JsonParseException
            || t is JSONException
            || t is ParseException
            || t is MalformedJsonException
        ) {
            errCode=HttpManager.PARSE_ERROR
            errMsg="解析错误"

        } else if (t is SocketException) {
            errCode=HttpManager.REQUEST_TIMEOUT
            errMsg="网络连接错误，请重试"


        } else if (t is SocketTimeoutException) {
            errCode=HttpManager.REQUEST_TIMEOUT
            errMsg="网络连接超时"

        } else if (t is SSLHandshakeException) {
            errCode=HttpManager.SSL_ERROR
            errMsg="证书验证失败"

        } else if (t is UnknownHostException) {
            errCode=HttpManager.UNKNOW_HOST
            errMsg="网络错误，请切换网络重试"

        } else if (t is UnknownServiceException) {
            errCode=HttpManager.UNKNOW_HOST
            errMsg="网络错误，请切换网络重试"
        } else if (t is NumberFormatException) {
            errCode=HttpManager.PARSE_ERROR
            errMsg="数字格式化异常"
        } else {
            errCode=HttpManager.UNKNOWN
            errMsg="未知错误"
        }
        return RestfulResponse<T>(errCode, errMsg, false, null)
    }
}